package cn.jflow.boot.controller.App;

import bp.App.SDJDJ.Handler_GGZL;
import bp.da.Log;
import bp.da.LogType;
import bp.difference.SystemConfig;
import bp.sys.ResultObj;
import bp.tools.Json;
import bp.tools.MD5Utill;
import bp.tools.StringUtils;
import bp.wf.Dev2Interface;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 广州市政
 */
@RestController
@CrossOrigin(maxAge = 3600)
@RequestMapping("/WF/GZSZ")
public class GZSZController {

    public static Object Return_Info(int code, String msg, Object data)
    {
        Hashtable ht = new Hashtable();
        ht.put("code", code);
        ht.put("message", msg);
        ht.put("msg", msg);
        ht.put("data", data);
        return ht;
    }
    /**
     * 天眼数据查询对外接口
     * @param param  企业工商名称
     * @return
     */
    @PostMapping("/queryTYData")
    public Object queryTYData(@RequestBody JSONObject param){
        try{
            Boolean isTrue=checkSign(param);
            //签名判断
            if(!isTrue){
                return Return_Info(500,"执行失败","签名失败");
            }
            //查询key
            String key = param.get("key").toString();
            // token可以从 数据中心 -> 我的接口 中获取
            String tytoken = SystemConfig.getAppSettings().get("gzsz_tyToken").toString();
            String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?keyword="+key;
            String result = executeGet(url, tytoken);
            System.out.println("天眼数据返回信息:");
            System.out.println(result);
            return Return_Info(200,"执行成功",result);
        }catch (Exception e){
            return Return_Info(500,"执行失败",e.getMessage());
        }
    }

    /**
     * 天眼数据查询对内选择接口
     * @param key  企业工商名称
     * @return
     */
    @RequestMapping ("/queryTYInfo2Select")
    public Object queryTYInfo2Fill(String key,String token){
        try{
            if(StringUtils.isEmpty(key)){
                return Return_Info(500,"执行失败","key不能为空");
            }
            Dev2Interface.Port_LoginByToken(token);
            // token可以从 数据中心 -> 我的接口 中获取
            String tytoken = SystemConfig.getAppSettings().get("gzsz_tyToken").toString();
            String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?keyword="+key;
            String result = executeGet(url, tytoken);
            System.out.println("天眼数据返回信息:");
            System.out.println(result);
            Log.DebugWriteError("天眼数据返回信息:" + result);
            //获得原始数据.
            JSONObject json = JSONObject.fromObject(result);
            int code=json.getInt("error_code");
            if(code!=0){
                System.out.println("天眼数据查询对内自动填充接口");
                return Return_Info(500,"执行失败",json.getString("reason"));
            }
            JSONObject redata=json.getJSONObject("result");
            //天眼返回的字段key
            String[] tyData={"name","regLocation","legalPersonName","alias","businessScope","creditCode"};
            //项目需要的字段key
            String[] xyData={"CR_Name","CR_UnitPlace","CR_LegalPerson","CR_Fax","CR_Scope","creditCode"};
            for(int i=0;i<tyData.length;i++){
                redata.put(xyData[i],redata.getString(tyData[i]));
            }
            redata.put("Name",redata.getString("CR_Name"));
            redata.put("No",redata.getString("id"));
            return redata.toString();
        }catch (Exception e){
            e.printStackTrace();
            return Return_Info(500,"执行失败",e.getMessage());
        }
    }

    /**
     * 天眼数据查询对内自动填充接口
     * @param key  企业工商名称
     * @return
     */
    @RequestMapping ("/queryTYInfo2Tc")
    public Object queryTYInfo2Filltc(String key,String token){
        try{
            if(StringUtils.isEmpty(key)){
                return Return_Info(500,"执行失败","key不能为空");
            }
            Dev2Interface.Port_LoginByToken(token);
            // token可以从 数据中心 -> 我的接口 中获取
            String tytoken = SystemConfig.getAppSettings().get("gzsz_tyToken").toString();
            String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?keyword="+key;
            String result = executeGet(url, tytoken);
            System.out.println("天眼数据返回信息:");
            System.out.println(result);
            Log.DebugWriteError("天眼数据返回信息:" + result);
            //获得原始数据.
            JSONObject json = JSONObject.fromObject(result);
            int code=json.getInt("error_code");
            if(code!=0){
                System.out.println("天眼数据查询对内自动填充接口");
                return Return_Info(500,"执行失败",json.getString("reason"));
            }
            JSONObject redata=json.getJSONObject("result");
            //天眼返回的字段key
            String[] tyData={"name","regLocation","legalPersonName","alias","businessScope","creditCode"};
            //项目需要的字段key
            String[] xyData={"CR_Name","CR_UnitPlace","CR_LegalPerson","CR_Fax","CR_Scope","creditCode"};
            for(int i=0;i<tyData.length;i++){
                redata.put(xyData[i],redata.getString(tyData[i]));
            }
            redata.put("Name",redata.getString("CR_Name"));
            return redata.toString();
        }catch (Exception e){
            e.printStackTrace();
            return Return_Info(500,"执行失败",e.getMessage());
        }
    }
    /**
     * http get请求
     * @param url 接口url
     *
     * @param token token
     * @return  返回接口数据
     */
    protected static String executeGet(String url, String token) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {

            HttpGet get = new HttpGet(url);
            // 设置header
            get.setHeader("Authorization",token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }
    /**
     * 签名认证
     * @return
     */
    private  Boolean checkSign(JSONObject param){
        try {
            //帐号
            String userNo = param.get("userNo").toString();
            //时间戳
            Long timestamp = Long.parseLong(param.get("timestamp").toString());
            //签名
            String sign = param.get("sign").toString();
            //当前时间
            Long timesNow = System.currentTimeMillis();
            //获取当前分钟数
            Long mins = (timesNow - timestamp) / (1000 * 60);
            if (mins > 5) {
                return false;
            }
            String signStr = userNo + "_" + timestamp;
            String signMD5 = MD5Utill.MD5Encode(signStr, "UTF-8");
            //签名判断
            if (!signMD5.equals(sign)) {
                return false;
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }
    public static void main(String[] args) {
        String tytoken = "d9781985-aeb8-43d5-abf8-82de78e605bb";
        String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?keyword=济南驰骋信息技术有限公司";
        String result = executeGet(url, tytoken);
        System.out.println(result);
    }

//*************************************模拟数据接口********************************************************************************

    //    public Map<String,Object> PostMockData() {
//        // 构建返回的假数据
//        Map<String, Object> dataMap = new HashMap<>();
//        dataMap.put("No", 1111255452);
//        dataMap.put("Name", "济南驰骋信息技术有限公司");
//
//        // 转换为字符串形式的 JSON（与你的输出一致）
//        String dataJsonString = Json.ToJson(dataMap);
//
//        // 构建最终返回结果
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", 200);
//        response.put("data", dataJsonString);  // 返回字符串化的 JSON
//        response.put("message", "执行成功");
//        response.put("msg", "执行成功");
//
//        return response;
//    }
    @RequestMapping("/mockData")
    public String PostMockData() {
        // 构建返回的假数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("No", 1111255452);
        dataMap.put("Name", "济南驰骋信息技术有限公司");
        dataMap.put("CR_LegalPerson", "周总");
        //天眼返回的字段key用来填充数据
        String[] tyData={"name","CR_LegalPerson"};
        //项目需要的字段key用来填充数据
        String[] xyData={"CR_Name","CR_LegalPerson"};
        for(int i=0;i<tyData.length;i++){
            dataMap.put(xyData[i],dataMap.get(tyData[i]));
        }
        // 转换为字符串形式的 JSON（与你的输出一致）
        String dataJsonString = Json.ToJson(dataMap);
        return dataJsonString;
    }

    @RequestMapping("/mockData1")
    public String PostMockData1() {
        // 构建返回的假数据
        Map<String, Object> dataMap = new HashMap<>();

        dataMap.put("Name", "济南驰骋信息技术有限公司");
        dataMap.put("CR_LegalPerson", "周总");
        //天眼返回的字段key用来填充数据
        String[] tyData={"name","CR_LegalPerson"};
        //项目需要的字段key用来填充数据
        String[] xyData={"CR_Name","CR_LegalPerson"};
        for(int i=0;i<tyData.length;i++){
            dataMap.put(xyData[i],dataMap.get(tyData[i]));
        }
        // 转换为字符串形式的 JSON（与你的输出一致）
        String dataJsonString = Json.ToJson(dataMap);
        return dataJsonString;
    }

}

